<template>
  <div class="client-status">
    <h1>客户端状态监控</h1>

    <div class="filters">
      <select v-model="filterType" @change="fetchClients">
        <option value="all">所有客户端</option>
        <option value="online">仅在线</option>
        <option value="offline">仅离线</option>
      </select>

      <input
        type="text"
        v-model="searchQuery"
        placeholder="搜索客户端名称或ID..."
        @input="handleSearch"
      />
    </div>

    <div class="clients-table-container">
      <table class="clients-table">
        <thead>
          <tr>
            <th>客户端ID</th>
            <th>名称</th>
            <th>类型</th>
            <th>状态</th>
            <th>最后心跳</th>
            <th>操作</th>
          </tr>
        </thead>
        <tbody>
          <tr v-for="client in filteredClients" :key="client.client_id">
            <td>{{ client.client_id }}</td>
            <td>{{ client.client_name }}</td>
            <td>
              <span class="client-type" :class="client.client_type">
                {{ formatClientType(client.client_type) }}
              </span>
            </td>
            <td>
              <span class="status-indicator" :class="client.is_online ? 'online' : 'offline'">
                {{ client.is_online ? '在线' : '离线' }}
              </span>
            </td>
            <td>
              {{ client.last_heartbeat ? formatTime(client.last_heartbeat) : '从未' }}
            </td>
            <td>
              <button
                @click="sendTestAlert(client.client_id)"
                class="btn-test-alert"
              >
                发送测试提醒
              </button>
            </td>
          </tr>
        </tbody>
      </table>

      <div v-if="filteredClients.length === 0" class="no-clients">
        没有找到符合条件的客户端
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue'
import axios from 'axios'

const API_BASE_URL = import.meta.env.VITE_API_BASE_URL || 'http://localhost:8000'

// 状态管理
const clients = ref([])
const filterType = ref('all')
const searchQuery = ref('')
const isLoading = ref(false)

// 格式化客户端类型
const formatClientType = (type) => {
  const types = {
    'windows': 'Windows',
    'mac': 'macOS',
    'android': 'Android',
    'unknown': '未知'
  }
  return types[type] || type
}

// 格式化时间
const formatTime = (timeString) => {
  const date = new Date(timeString)
  return date.toLocaleString()
}

// 获取客户端列表
const fetchClients = async () => {
  try {
    isLoading.value = true
    const response = await axios.get(`${API_BASE_URL}/api/clients`)
    clients.value = response.data
  } catch (error) {
    console.error('获取客户端列表失败:', error)
  } finally {
    isLoading.value = false
  }
}

// 过滤客户端
const filteredClients = computed(() => {
  return clients.value.filter(client => {
    // 类型过滤
    if (filterType.value === 'online' && !client.is_online) return false
    if (filterType.value === 'offline' && client.is_online) return false

    // 搜索过滤
    if (searchQuery.value) {
      const query = searchQuery.value.toLowerCase()
      const matchesId = client.client_id.toLowerCase().includes(query)
      const matchesName = client.client_name.toLowerCase().includes(query)
      if (!matchesId && !matchesName) return false
    }

    return true
  })
})

// 搜索处理
const handleSearch = (e) => {
  // 延迟搜索以避免频繁请求
  clearTimeout(window.searchTimeout)
  window.searchTimeout = setTimeout(() => {
    // 搜索逻辑由computed自动处理
  }, 300)
}

// 发送测试提醒
const sendTestAlert = async (clientId) => {
  try {
    await axios.post(`${API_BASE_URL}/api/alerts`, {
      title: '测试提醒',
      content: `这是发送给客户端 ${clientId} 的测试提醒`,
      alert_time: new Date().toISOString(),
      repeat: 'none'
    })
    alert('测试提醒已发送')
  } catch (error) {
    console.error('发送测试提醒失败:', error)
    alert('发送测试提醒失败')
  }
}

// 页面加载时获取客户端列表
onMounted(() => {
  fetchClients()
  // 每10秒刷新一次客户端状态
  setInterval(fetchClients, 10000)
})
</script>

<style scoped>
.client-status {
  max-width: 1200px;
  margin: 0 auto;
}

.filters {
  display: flex;
  gap: 15px;
  margin: 20px 0;
  align-items: center;
}

.filters select,
.filters input {
  padding: 8px 12px;
  border: 1px solid #ddd;
  border-radius: 4px;
}

.filters select {
  width: 150px;
}

.filters input {
  flex: 1;
  max-width: 400px;
}

.clients-table-container {
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  overflow: hidden;
}

.clients-table {
  width: 100%;
  border-collapse: collapse;
}

.clients-table th,
.clients-table td {
  padding: 12px 15px;
  text-align: left;
  border-bottom: 1px solid #f1f1f1;
}

.clients-table th {
  background-color: #f8f9fa;
  font-weight: bold;
  color: #2c3e50;
}

.status-indicator {
  padding: 4px 8px;
  border-radius: 4px;
  font-size: 0.8rem;
}

.status-indicator.online {
  background-color: #eafaf1;
  color: #27ae60;
}

.status-indicator.offline {
  background-color: #fdedeb;
  color: #e74c3c;
}

.client-type {
  padding: 4px 8px;
  border-radius: 4px;
  font-size: 0.8rem;
}

.client-type.windows {
  background-color: #e6f7ff;
  color: #1890ff;
}

.client-type.mac {
  background-color: #fff2e8;
  color: #fa8c16;
}

.client-type.android {
  background-color: #f6ffed;
  color: #52c41a;
}

.client-type.unknown {
  background-color: #f5f5f5;
  color: #8c8c8c;
}

.btn-test-alert {
  padding: 6px 12px;
  background-color: #3498db;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 0.8rem;
  transition: background-color 0.3s;
}

.btn-test-alert:hover {
  background-color: #2980b9;
}

.no-clients {
  text-align: center;
  padding: 40px 20px;
  color: #7f8c8d;
}
</style>
